<?php
$width = 100;
$height = 50;
$len = 4;
$str = range('a', 'z') + range('A', 'Z') + range(0, 9);
$img = imagecreatetruecolor($width, $height);

$gray = imagecolorallocatealpha($img, 250, 250, 250, 90);
imagefill($img, 0, 0, $gray);

$result = ''; //验证码字符串
$color = imagecolorallocatealpha($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(10, 20));
for ($i = 0; $i < $len; $i++) {
    $size = mt_rand(18, 28);
    $angle = mt_rand(-45, 45);
    $x = 5 + $i * 25;
    $y = mt_rand(22, 38);
    $font = 'fonts/fzyh.ttf';
    $text = $str[mt_rand(0, count($str) - 1)];
    $result .= $text;
    imagettftext($img, $size, $angle, $x, $y, $color, $font, $text);
}

session_start();
$_SESSION['captcha'] = $result;
$_SESSION['captchatime'] = time();

//干扰文字
for ($i = 0; $i < 5; $i++) {
    $size = mt_rand(12, 38);
    $angle = mt_rand(0, 360);
    $x = mt_rand(0, $width);
    $y = mt_rand(0, $height);
    $color = imagecolorallocatealpha($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(100, 127));
    $font = 'fonts/fzyh.ttf';
    $text = $str[mt_rand(0, count($str) - 1)];
    imagettftext($img, $size, $angle, $x, $y, $color, $font, $text);
}

//干扰文字
for ($i = 0; $i < 10; $i++) {
    $size = mt_rand(12, 38);
    $angle = mt_rand(0, 360);
    $x = mt_rand(0, $width);
    $y = mt_rand(0, $height);
    $color = imagecolorallocatealpha($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(110, 120));
    $font = 'fonts/fzyh.ttf';
    $text = $str[mt_rand(0, count($str) - 1)];
    imagettftext($img, $size, $angle, $x, $y, $color, $font, $text);
    if ($i % 5 == 0) {
        $x = mt_rand(0, $width);
        $y = mt_rand(0, $height);
        $color = imagecolorallocatealpha($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(120, 127));
        imagefilledellipse($img, $x, $y, $size, $size, $color);
    }
}

for($i=0;$i<=30;$i++){
    imagesetthickness($img,mt_rand(1,8));
    $color = imagecolorallocatealpha($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(100, 120));
    imagearc($img,rand(1,300),rand(1,300),rand(1,300),rand(1,300),rand(1,300),rand(1,300),$color);
}

header('content-type:image/png');
imagepng($img);
imagedestroy($img);
